// const baseUrl = 'http://192.168.201.113:8002'
// const baseUrl = 'http://192.168.233.78:8000'
const baseUrl = 'https://sindlearning.sindvision.com'

export const toPromise = (wxApi, params) => {
  return new Promise((resolve, reject) => {
    wxApi({
      ...params,
      success: resolve,
      fail: reject,
    })
  })
}

export const getCode = async () => {
  const getAndSave = async () => {
    const { code } = await toPromise(wx.login)
    wx.setStorageSync('code', code)
    return code
  }
  return getAndSave()

  try {
    await wx.checkSession()
    const savedCode = wx.getStorageSync('code')
    if (savedCode) {
      return savedCode
    } else {
      return getAndSave()
    }
  } catch (e) {
    return getAndSave()
  }
}

/** @param {string} url */
const addCodeQuery = async url => {
  const code = await getCode()
  if (url.includes('?')) {
    return `${url}&code=${code}`
  }
  return `${url}?code=${code}`
}

export const request = async params => {
  if (typeof params === 'string') {
    params = { url: params }
  }
  const url = await addCodeQuery(baseUrl + params.url)
  const res = await toPromise(wx.request, {
    ...params,
    url,
    header: {
      ...(params.header || {}),
      Cookie: wx.getStorageSync('token')
    }
  })
  const { statusCode = 0 } = res || {}
  if (statusCode >= 300) {
    const { error, message } = res.data || {}
    const msg = error || message || res.data || `${res.statusCode}错误`
    if (statusCode === 403) {
      wx.redirectTo({
        url: '/pages/register/index',
      })
    } else {
      wx.showModal({ title: msg, icon: 'error' })
    }
    return Promise.reject(new Error(msg))
  }
  if (params.saveToken) {
    wx.setStorageSync('token', res.header['Set-Cookie'])
  }
  return res.data
}

export const post = params => {
  return request({
    ...params,
    method: 'POST',
    header: {
      ...(params.header || {}),
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export const uploadFile = async ({ file, dest = '' }) => {
  const res = await toPromise(wx.uploadFile, {
    url: baseUrl + '/api/upload',
    filePath: file.tempFilePath,
    name: 'file',
    formData: {
      dest,
      willOverwrite: true,
      file: file.tempFilePath
    }
  })
  if (res.statusCode >= 300) {
    return new Error(res.data)
  }
  return res.data
}

export const getUserProfile = () => request('/api/portal/homePage/')
